
import { defineStore } from "pinia";
import type { RecordLocation } from '@/types/book'
export const useBookStore = defineStore('book', {
    state: () => {
        return {
            recentBooks: [] as string[],
            recordLocation: {} as { [key: string]: RecordLocation },
            deletedBooks: [] as string[],
            favoriteBooks: [] as string[],
        }
    },
    getters: {

    },
    actions: {
        addRecentBooks(bookKey: string) {
            return new Promise((resolve, reject) => {
                if (this.recentBooks.includes(bookKey)) {
                    reject('图书已经存在~');
                } else {
                    this.recentBooks.push(bookKey)
                    resolve(true)
                }
            })
        },
        deleteRecentBook(bookKey: string): boolean {
            const index = this.recentBooks.indexOf(bookKey);
            if (index > -1) {
                this.recentBooks.splice(index, 1)
                return true
            } else {
                return false;
            }
        },
        /**将图书移入回收站 */
        moveBookToRecycle(bookKey: string) {
            return new Promise((resolve, reject) => {
                if (!this.deletedBooks.includes(bookKey)) {
                    this.deletedBooks.push(bookKey)
                    resolve(true)
                } else {
                    reject('此书已经在回收站');
                }
            })
        },
        /**将图书从回收站移除 */
        removeBookFromRecycle(bookKey: string): boolean {
            const index = this.deletedBooks.indexOf(bookKey);
            if (index > -1) {
                this.deletedBooks.splice(index, 1)
                return true
            } else {
                return false;
            }
        },
        addFavoriteBooks(bookKey: string) {
            return new Promise((resolve, reject) => {
                if (this.favoriteBooks.includes(bookKey)) {
                    reject('图书已经在我的喜爱里了~');
                } else {
                    this.favoriteBooks.push(bookKey)
                    resolve(true)
                }
            })
        },
        deleteFavoriteBook(bookKey: string): boolean {
            const index = this.favoriteBooks.indexOf(bookKey);
            if (index > -1) {
                this.favoriteBooks.splice(index, 1)
                return true
            } else {
                return false;
            }
        },
        addrecordLocation(bookKey: string,locationInfo:RecordLocation) {
            this.recordLocation[bookKey] = locationInfo;
        },
        
    },
    persist: {
        pick: ['recentBooks', 'recordLocation', 'favoriteBooks', 'deletedBooks']
    }
})